package 课上练习0420_scala_method$$class

/**
 * 继承、特质
 */
object Scala_05Inherit {
  def main(args: Array[String]): Unit = {
    val c1: Animal = new Cat("家猫", 20)
    println(c1.height)  //12，说明已经被子类覆盖了
    c1.show(2)
    if (c1.isInstanceOf[Cat]) {
      c1.asInstanceOf[Cat].attack()
      c1.asInstanceOf[Cat].log("使用特质中的方法")
    }
    // 动态扩展
    val c2 = new Cat("夜猫", 30) with Trait03 {
      override def dynamicTFEmpty: Unit = println("动态实现2")
    }
    c2.dynamicTF()
  }
}

class Animal(var name: String, var age: Int) {
  val height = 10
  var color = "蓝色"
  def show(a: Int) = {

  }
}

/**
 * 1、父类主构造器只能被子类的主构造器调用；
 * 2、如果子类没有写主构造器，继承的父类的字段要给值
 * 3、子类可以同父类一起实现主构造器
 */
//class Cat extends Animal(name = "", age = 10) {
class Cat(name: String, age: Int) extends Animal(name , age) with Trait01 with Trait02 {
  // 字段重写，必须保证字段类型是val
  override val height: Int = 12

  override def show(a: Int): Unit = { // 这里的override去掉报错
    super.show(3) // 调用父类同名的方法
    // 写自己的功能
    println("这是子类的show方法")
  }

  def attack() = {
    println("子类特有方法")
  }

  override def trait01F(): Unit = ???
  override def trait02F(): Unit = ???
}

trait Trait01 { def trait01F() }

trait Trait02 {
  def trait02F()

  def log(msg: String): Unit = {
    println(msg)
  }
}

// 特质也可以继承父类、特质
trait Trait03 extends Animal with Trait02 {
  def dynamicTF(): Unit = {
    println("动态引入")
  }

  def dynamicTFEmpty
}
